#include "FileSearch.h"

#include "GetFiles.h"

unsigned int folderCount = 0; 
QMutex mutex;

FileSearch::FileSearch ( QStringList location,ResultCollector *result,QObject *parent )
		: QThread ( parent )
{
	this->location = location;
	this->result = result;
	
}


FileSearch::~FileSearch()
{
	wait ( -1 );
	//qDebug() << QTime::currentTime().toString("hh::mm::ss::zzz");

}

void FileSearch::distribute()
{
	int count;
	for ( int i =0; i<location.count();++i )
	{
		//qDebug() << location.at(i);
		QDir dir ( location.at ( i ) );

		QStringList subDir = dir.entryList ( QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
		

		mutex.lock();
		
		folderCount = folderCount + subDir.count();
		count = folderCount;
		//qDebug() <<"FOLDER COUNT :"<<count;

		mutex.unlock();			
		
		for ( int j =0; j<subDir.count();++j )
		{
			subDir[j] = dir.absoluteFilePath(subDir.at(j));
			//qDebug() << "         " <<subDir[j];
		}

		FileSearch subSearch ( subDir,result );

		/*    foreach (QString subdir, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot))
			{
			       list += findFiles(startDir + "/" + subdir);

			       Result total = QtConcurrent::mappedReduced(list, findFiles, reduce);
			}
		*/
	
		subSearch.search();

		GetFiles total(location.at(i),result);
		total.run();
	}

}

void FileSearch::run()
{
	distribute();

	//QStringList total = QtConcurrent::mappedReduced ( location, findFiles, reduce );

	
/*
	for ( int i =0; i<total.count();++i )
	{
		qDebug () << total.at(i);
	}
*/
}

void FileSearch::search ( QStringList location )
{
	this->location = location;
	search();
}

void FileSearch::search ( QString location )
{
	search ( QStringList ( location ) );

}

void FileSearch::search()
{
	start();
}
